package com.crm.web.controller;

import com.crm.entity.Chance;
import com.crm.service.ChanceService;
import com.crm.service.IUserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/chance")
public class ChanceController {

    @Resource
    ChanceService chanceService;
    @Resource
    IUserService userService;

    @RequestMapping("/list")
    public String list(@RequestParam(required = false, defaultValue = "") String custName,
                       @RequestParam(required = false, defaultValue = "") String chcTitle,
                       @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                       Model model) {
        Sort sort = new Sort(Sort.Direction.ASC, "chcId");
        Pageable pageable = PageRequest.of(pageIndex - 1, 3, sort);
        Page<Chance> page = chanceService.findByChcCustNameLikeAndChcDescLike(custName, chcTitle, pageable);
        model.addAttribute("chancePage", page);
        model.addAttribute("custName", custName);
        model.addAttribute("chcTitle", chcTitle);
        return "chance/list";
    }

    @RequestMapping("/save")
    public String save(Chance chance) {
        try{
            chanceService.save(chance);
            return "redirect:/chance/list";
        }catch (Exception e){
            return "chance/add";
        }
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam Integer chcId,Model model) {
        model.addAttribute("users",userService.findAll());
        model.addAttribute("chance",chanceService.getChanceByChcId(chcId));
        return "chance/edit";
    }

    @RequestMapping("/add")
    public String add(Model model) {
        model.addAttribute("users",userService.findAll());
        return "chance/add";
    }

    @RequestMapping("/del/{chcId}")
    @ResponseBody
    public Map del(@PathVariable Integer chcId) {
        Map<String, String> map = new HashMap<>();
        try{
            chanceService.del(chcId);
            map.put("delResult","true");
        }catch (Exception e){
            map.put("delResult","false");
        }
        return map;
    }

}
